<template>
  <header class="main-header">
    <div class="header-content">
      <div class="logo-section">
        <div class="logo-icon">🎭</div>
        <h1>Echo Role</h1>
        <span class="version-tag">Beta</span>
      </div>
      
      <nav class="main-nav">
        <el-button 
          :class="['nav-item', { active: currentView === 'novels' || currentView === 'novel-detail' }]"
          @click="$emit('navigate', 'novels')"
          type="text"
        >
          📚 {{ $t('nav.novels') }}
        </el-button>
        <el-button 
          :class="['nav-item', { active: currentView === 'profile' }]"
          @click="$emit('navigate', 'profile')"
          type="text"
        >
          👤 {{ $t('nav.profile') }}
        </el-button>
      </nav>
      
      <div class="header-controls">
        <!-- 主题切换按钮 -->
        <ThemeToggle />
        
        <!-- 语言切换器 -->
        <el-dropdown @command="handleLanguageChange" class="language-dropdown">
          <el-button text class="lang-btn">
            <span>{{ supportedLocales.find(l => l.value === currentLanguage)?.flag || '🌐' }}</span>
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item 
                v-for="locale in supportedLocales"
                :key="locale.value"
                :command="locale.value"
                :class="{ 'is-active': currentLanguage === locale.value }"
              >
                {{ locale.flag }} {{ locale.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <div class="user-info">
          <el-avatar :size="32" class="user-avatar">
            {{ userStore.currentUser?.username?.charAt(0)?.toUpperCase() || 'U' }}
          </el-avatar>
          <span class="username">{{ userStore.currentUser?.username || $t('common.user') }}</span>
        </div>
        
        <el-dropdown @command="handleCommand">
          <el-button type="text" class="settings-btn">
            <el-icon><Setting /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">{{ $t('nav.profile') }}</el-dropdown-item>
              <el-dropdown-item command="preferences">{{ $t('nav.preferences') }}</el-dropdown-item>
              <el-dropdown-item command="logout" divided>{{ $t('nav.logout') }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </header>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/modules/user'
import { Setting, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { setLocale, getCurrentLocale, supportedLocales, type SupportedLocale } from '../../i18n'
import ThemeToggle from './ThemeToggle.vue'

interface Props {
  currentView: string
}

defineProps<Props>()
const emit = defineEmits<{
  navigate: [view: string]
  languageChange: [locale: SupportedLocale]
}>()

const router = useRouter()
const userStore = useUserStore()
const { t } = useI18n()

// 语言切换相关
const currentLanguage = ref<SupportedLocale>(getCurrentLocale())

const handleLanguageChange = (locale: SupportedLocale) => {
  console.log('[AppHeader] Language change requested:', locale)
  currentLanguage.value = locale
  setLocale(locale)
  emit('languageChange', locale)
  ElMessage.success(t('common.languageChanged'))
}

// 监听语言变化事件
const handleLanguageChangedEvent = (event: Event) => {
  const customEvent = event as CustomEvent
  currentLanguage.value = customEvent.detail.locale
}

onMounted(() => {
  // 确保当前语言与存储的语言同步
  currentLanguage.value = getCurrentLocale()
  window.addEventListener('language-changed', handleLanguageChangedEvent as EventListener)
})

onUnmounted(() => {
  window.removeEventListener('language-changed', handleLanguageChangedEvent as EventListener)
})

const handleCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'preferences':
      router.push('/preferences')
      break
    case 'logout':
      logout()
      break
  }
}

const logout = async () => {
  try {
    await ElMessageBox.confirm(
      t('auth.logout.confirmMessage'), 
      t('auth.logout.confirmTitle'), 
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )
    
    await userStore.logout()
    ElMessage.success(t('auth.logout.success'))
    
    // 退出登录后跳转到首页而不是登录页面
    router.push('/')
  } catch (error) {
    // 用户取消操作
  }
}
</script>

<script lang="ts">
export default {
  name: 'AppHeader'
}
</script>

<style scoped>
.main-header {
  background: var(--surface);
  border-bottom: 1px solid var(--border);
  padding: 0 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  z-index: 100;
  transition: all 0.3s ease;
}

/* 深色模式下的头部 */
:global(.dark) .main-header {
  background: var(--surface);
  border-bottom-color: var(--border);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64px;
  max-width: 1800px;
  margin: 0 auto;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 32px;
  animation: logoFloat 3s ease-in-out infinite;
}

@keyframes logoFloat {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-3px); }
}

.logo-section h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.version-tag {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 2px 8px;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 600;
  text-transform: uppercase;
}

.main-nav {
  display: flex;
  gap: 16px;
  margin-left: 20px;
}

.nav-item {
  font-size: 16px;
  color: var(--text-secondary);
  padding: 8px 12px;
  border-radius: 12px;
  transition: all 0.2s ease;
}

.nav-item:hover {
  background: var(--background);
  color: var(--primary-color);
}

.nav-item.active {
  background: linear-gradient(135deg, #667eea20, #764ba220);
  color: var(--primary-color);
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: var(--background);
  border-radius: 20px;
}

.username {
  font-weight: 500;
  color: var(--text-primary);
}

.settings-btn {
  font-size: 18px;
  color: var(--text-secondary);
}

.language-dropdown {
  margin-right: 8px;
}

.lang-btn {
  color: var(--text-secondary);
  font-size: 16px;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.lang-btn:hover {
  background: var(--background);
  color: var(--primary-color);
}

.lang-btn span {
  margin-right: 4px;
}

:deep(.el-dropdown-menu__item.is-active) {
  color: #667eea;
  font-weight: 600;
}
</style> 